<?php

class ui_datatable extends ui
{
	function init($name=null,$columns=array(),$max_rows=null)
	{
		global $ti;

		parent::init(__FILE__,'table',array('class'=>'datatable',));
		$this->name = (is_null($name))?get_class($this):$name;
		echo('name is: '.$this->name);

		$this->columns = array();
		$this->rows = null;
		$this->page = (empty($ti->data[$this->class.'_page']))?0:$ti->data[$this->class.'_page'];
		$this->max_rows = (is_null($max_rows))?$ti->config['template.datatable.max_rows']:$max_rows;
		$this->max_page = null;
		$this->query = new ti_query_builder();
		$this->query->page($this->page,$this->max_rows);
		
		$this->add(new ui_datatable_header());
		for ($i = 0; $i < count($columns); $i++)
		{
			$columns[$i]->index = $i;
			$this->last->add($columns[$i]);
		}
		#$ti->log('cols created');
		
		for ($i = 0; $i < $this->max_rows; $i++)
		{
			$this->add(new ui_datatable_row($i));
			#$ti->log('rows created: '.$this->max_rows);
			for ($j = 0; $j < count($this->nodes[0]->nodes); $j++)
			{	
				#$ti->log($this->nodes[0]->nodes[$j]->get_cell_class());
				$class = $this->nodes[0]->nodes[$j]->get_cell_class();
				$this->last->add(new ui_datatable_cell($i,$j,$this->nodes[0]->nodes[$j]->db_name));
				if(!is_null($class))
				{
					$this->last->last->add(new $class());
				}
				$this->last->last->text($this->nodes[0]->nodes[$j]->template);
			}
		}
		#$ti->log('rows created');
		$this->add(new ui_datatable_footer(&$this));
		
	}
	
	function pre_render($data=null)
	{
		global $ti;
		parent::pre_render($data);
		$this->rows = $this->query->row_count();
		$this->max_page = ceil($this->rows / $this->max_rows);
		$pages = array();
		
		for ($i = 0; $i < count($this->nodes[0]->nodes); $i++)
		{		
			if($ti->data[$this->class.'_sort_col'].'' == $i.'')
			{
				$this->query->sort($this->nodes[0]->nodes[$i]->db_name,$ti->data[$this->class.'_sort_dir']);
			}
		}
		
		for ($i = 0; $i < $this->max_page; $i++)
		{
			$pages[] = 'Page '.($i + 1).' of '.$this->max_page;
		}
		#print_r($pages);
		$this->page_select->source = $pages;
		
		#print_r($this->query);
		$this->result = $this->query->execute();
		
		$ti->swap['js'] .= 'new ti.datatable(\'user/get_block_data\',\''.$this->name.'\','.$this->result->num_rows().');';
	}
	
	function render_data($do_swap=false)
	{
		global $ti;
		
		$this->pre_render();
		for ($i = 1; $i < (count($this->nodes) - 1); $i++)
		{
			$this->result->next();
			#echo('rendering: '.print_r($this->result->data,true));
			for ($j = 0; $j < count($this->nodes[$i]->nodes); $j++)
			{
				$this->nodes[$i]->nodes[$j]->pre_render($this->result->data);
				$this->nodes[$i]->nodes[$j]->render_nodes($this->result->data);
				$this->nodes[$i]->nodes[$j]->post_render($this->result->data);
				$ti->swap[$this->name.'_'.($i - 1).'x'.$j] = $this->nodes[$i]->nodes[$j]->html;
				$ti->swap['js'] .= $this->nodes[$i]->nodes[$j]->js;
			}
		}
	}
	
	function get_data()
	{
		global $ti;
		$this->render_data(true);
		$ti->ajax();
	}
}

?>